import React, { useEffect, useRef, useState } from 'react';
import { FieldsGrid, TitleGrid } from '../../stores/definitions';
import { t } from '@lingui/macro';
import { Button, Dialog, Form } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import TicketInfoTable from './TicketInfoTable';
import DrawerFooter from '@/components/DrawerFooter';

const FromItem = Form.Item;

const TaskInfo = (props) => {
  const {
    task,
    isEditModal,
    onCancel,
    onSubmit,
  } = props;
  const [formData, setFormData] = useState({});
  const editCtx = useRef({ origin: {}, changed: {} }).current;

  useEffect(() => {
    editCtx.origin = _.cloneDeep(task);
    setFormData(task);
  }, []);


  const handleCancel = () => {
    if (!_.isEmpty(editCtx.changed)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(formData, name, value);
    setFormData({ ...formData });

    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  return (
    <Form
      inline
      isPreview={!isEditModal}
      value={formData}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基本信息`} />
      <FieldsGrid
        formData={task}
        mode="view"
        fields={['id', 'state', 'crDate', 'cancelTime', 'carrierCompanyName', 'driverInfo[0].name', 'driverInfo[0].phone', 'driverInfo[0].licenseNo', 'carrierPrice', 'fleetSettlement', 'driverServiceFee', 'driverSettlement']}
      />
      <TitleGrid title={t`行程信息`} />
      <FieldsGrid
        formData={task}
        mode="view"
        fields={[
          'startArea', 'orderBaseModel.beginName', 'tickets[0].writeOffDate', 'endArea', 'orderBaseModel.endName',
        ]}
      />
      <TitleGrid title={t`车票信息`} />
      <TicketInfoTable dataSource={task.tickets} />
      <TitleGrid title={t`备注`} />
      <FieldsGrid
        formData={formData}
        mode={isEditModal ? 'edit' : 'view'}
        fields={['remark', 'cancelRemark']}
      />
      <DrawerFooter>
        <FromItem>
          {isEditModal && <Form.Submit validate type="primary" onClick={() => onSubmit(formData)}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(TaskInfo);
